package com.secondmybatis.interceptor;

import com.secondmybatis.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求url
        StringBuffer url = request.getRequestURL();
        String uri = request.getRequestURI();
        // 2.判断请求路径中是否包含Login,如果包含，说明是登录操作，放行
        if(uri.contains("/login")){
            return true;
        }
        // 3.获取请求头中的令牌
        String token = request.getHeader("token");
        // 4.判断令牌是否存在，如果不存在，则响应401
        if(token ==null){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 5.解析token,如果解析失败，则响应401
        try {
            Map<String, Object> claims = JwtUtils.parseJwt(token);
        }catch (Exception e){
            e.printStackTrace();
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            // 不放行
            return false;
        }
        // 6.放行
        return true;

    }
}
